﻿using Microsoft.AspNetCore.Mvc;
using WMS.Common.WMS.Common;
using WMS.Model;
using WMS.Repository.IRepository;
using WMS.Service.IService;

namespace wmsWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RoleController : ControllerBase
    {
        private readonly IRoleService _roleService;
        private readonly ILogger<RoleController> _logger;

        public RoleController(IRoleService roleService, ILogger<RoleController> logger)
        {
            _roleService = roleService;
            _logger = logger;
        }

        /// <summary>
        /// 分页查询角色列表
        /// </summary>
        [HttpGet("GetRolePagedListAsync")]
        public async Task<ResultApi> GetRolePagedListAsync(string roleName, byte status = 1, int pageIndex = 1, int pageSize = 20)
        {
            try
            {
                var request = new RoleQueryRequest
                {
                    RoleName = roleName,
                    Status = status,
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };

                var result = await _roleService.GetRolePagedListAsync(request);
                return ResultHelper.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "角色分页查询失败");
                return ResultHelper.Error("500", "查询失败");
            }
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        [HttpPost("AddRoleAsync")]
        public async Task<ResultApi> AddRoleAsync([FromBody] AddRoleModelDto role)
        {
            try
            {
                if (string.IsNullOrEmpty(role.RoleName))
                {
                    return ResultHelper.Error("角色名不能为空！");
                }
                var (success, message) = await _roleService.AddRoleAsync(role.RoleName, role.RoleDesc);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加角色失败 - 角色名称: {role?.RoleName}");
                return ResultHelper.Error("500", "添加失败");
            }
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        [HttpPost("UpdateRoleAsync")]
        public async Task<ResultApi> UpdateRoleAsync([FromBody] UpdateRoleModelDto role)
        {
            try
            {
                if (role.Id <= 0)
                {
                    return ResultHelper.Error("请选择角色！");
                }

                var (success, message) = await _roleService.UpdateRoleAsync((long)role.Id, role.RoleName, role.RoleDesc, role.Status);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改角色失败 - 角色ID: {role?.Id}");
                return ResultHelper.Error("500", "修改失败");
            }
        }

        /// <summary>
        /// 启用禁用角色
        /// </summary>
        [HttpPost("UpdateRoleStatusAsync")]
        public async Task<ResultApi> UpdateRoleStatusAsync([FromBody] long roleId)
        {
            try
            {
                if (roleId <= 0)
                {
                    return ResultHelper.Error("请选择角色！");
                }
                var (success, message) = await _roleService.UpdateRoleStatusAsync(roleId);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新角色状态失败 - 角色ID: {roleId}");
                return ResultHelper.Error("500", "操作失败");
            }
        }

        /// <summary>
        /// 批量启用禁用角色
        /// </summary>
        [HttpPost("UpdateRolesStatusAsync")]
        public async Task<ResultApi> UpdateRolesStatusAsync([FromBody] List<long> ids)
        {
            try
            {
                if (ids == null || ids.Count == 0)
                {
                    return ResultHelper.Error("角色ID列表不能为空！");
                }
                var (success, message) = await _roleService.UpdateRolesStatusAsync(ids);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量更新角色状态失败 - 角色数量: {ids?.Count ?? 0}");
                return ResultHelper.Error("500", "操作失败");
            }
        }

        /// <summary>
        /// 获取用户角色穿梭数据
        /// </summary>
        [HttpPost("GetUserRoleInfoAsync")]
        public async Task<ResultApi> GetUserRoleInfoAsync([FromBody] long roleId)
        {
            try
            {
                if (roleId <= 0)
                {
                    return ResultHelper.Error("请选择角色！");
                }

                var (success, message, data) = await _roleService.GetUserRoleInfoAsync(roleId);
                if (success)
                {
                    return ResultHelper.Success(data, message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户角色信息失败 - 角色ID: {roleId}");
                return ResultHelper.Error("500", "获取失败");
            }
        }

        /// <summary>
        /// 绑定/解绑用户
        /// </summary>
        [HttpPost("IsBandUserAsync")]
        public async Task<ResultApi> IsBandUserAsync([FromBody] UserRoleModelDTO userRoleModelDTO)
        {
            try
            {
                if (userRoleModelDTO.UserIds == null || !userRoleModelDTO.UserIds.Any())
                {
                    return ResultHelper.Error("请选择用户！");
                }

                if (userRoleModelDTO.RoleId <= 0)
                {
                    return ResultHelper.Error("请选择角色！");
                }

                var (success, message) = await _roleService.IsBandUserAsync(userRoleModelDTO.IsBand, userRoleModelDTO.RoleId, userRoleModelDTO.UserIds);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"绑定/解绑用户失败 - 角色ID: {userRoleModelDTO?.RoleId}, 用户数量: {userRoleModelDTO?.UserIds?.Count ?? 0}, 操作类型: {(userRoleModelDTO?.IsBand == 1 ? "绑定" : "解绑")}");
                return ResultHelper.Error("500", "操作失败");
            }
        }

        /// <summary>
        /// 角色绑定菜单树
        /// </summary>
        [HttpGet("GetMenuTreeWithRoleStatusAsync")]
        public async Task<ResultApi> GetMenuTreeWithRoleStatusAsync(long roleId)
        {
            try
            {
                if (roleId <= 0)
                {
                    return ResultHelper.Error("请选择角色！");
                }

                var data = await _roleService.GetMenuTreeWithRoleStatusAsync(roleId);
                return ResultHelper.Success(data);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取菜单树失败 - 角色ID: {roleId}");
                return ResultHelper.Error("500", "获取失败");
            }
        }

        /// <summary>
        /// 解绑/绑定菜单
        /// </summary>
        [HttpPost("IsBindMenuAsync")]
        public async Task<ResultApi> IsBindMenuAsync([FromBody] RoleMenuModelDTO roleMenuModelDTO)
        {
            try
            {
                if (roleMenuModelDTO.RoleId <= 0)
                {
                    return ResultHelper.Error("请选择角色！");
                }

                if (roleMenuModelDTO.MenuIds == null || roleMenuModelDTO.MenuIds.Count <= 0)
                {
                    return ResultHelper.Error("请选择菜单！");
                }

                var (success, message) = await _roleService.IsBindMenuAsync(roleMenuModelDTO.RoleId, roleMenuModelDTO.MenuIds);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"绑定/解绑菜单失败 - 角色ID: {roleMenuModelDTO?.RoleId}, 菜单数量: {roleMenuModelDTO?.MenuIds?.Count ?? 0}");
                return ResultHelper.Error("500", "操作失败");
            }
        }
    }
}